package model

import (
	"fmt"
	"gorm.io/gorm"
	"tem/dto/common"
	"tem/dto/modelDto"
	"tem/global"
)

type Comment struct {
	common.IDModel `gorm:embedded`
	UserId         uint   `json:"userId" gorm:"column:user_id"`       //当前评论人的用户id
	ParentId       uint   `json:"parentId" gorm:"column:parent_id"`   //回复评论的id，如果为0，则表示该评论是一级评论
	InstantId      uint   `json:"instantId" gorm:"column:instant_id"` //评论所属文章的id
	Context        string `json:"context" gorm:"column:context"`      //评论内容
}

func (Comment) TableName() string {
	return "comment"
}

func (Comment) FindList(id uint, pageIndex int, pageSize int) ([]modelDto.CommentModel, int64, error) {
	var c []modelDto.CommentModel
	var totalNum int64
	err := global.DB.Table("comment").Select("id,context,parent_id,created_at,context,instant_id,user_id,"+
		"(select username as cnt from user where user.id = user_id) as username").Where("instant_id = ?", id).Count(&totalNum).Limit(pageSize).Offset(pageSize * (pageIndex - 1)).Scan(&c).Error
	if err != nil {
		return c, 0, err
	} else {
		fmt.Println(c, totalNum, nil)
		return c, totalNum, nil
	}
}

func (Comment) Create(c Comment) *gorm.DB {
	tx := global.DB.Create(&c)
	return tx

}
